<?php
/**
 * Created by PhpStorm.
 * User: a4041
 * Date: 2018/6/13
 * Time: 13:46
 */

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class ShopClerk extends Model
{
    use SoftDeletes;
    protected $guarded = ['id'];
    protected $hidden = ['updated_at','created_at','deleted_at','password'];
    /*
   * 一个用户有哪些角色
   */
    public function roles()
    {
        return $this->belongsToMany(ShopRole::class, 'shop_clerks', 'clerk_id', 'role_id')->withPivot(['clerk_id', 'role_id']);
    }

    /*
     * 是否有某个角色
     */
    public function isInRoles($roles)
    {
        return !! $roles->intersect($this->roles)->count();
    }

    /*
     * 是否有权限
     */
    public function hasPermission($permission)
    {
        return $this->isInRoles($permission->roles);
    }

    /*
     * 给用户分配角色
     */
    public function assignRole($roleName)
    {
        $role = ShopRole::where('name', $roleName)->first();
        return $this->roles()->save($role);
    }

    /*
     * 删除user和role的关联
     */
    public function deleteRole($role)
    {
        return $this->roles()->detach($role);
    }

    public function shop()
    {
        return $this->belongsTo(Shop::class,'shop_id','id');
    }
    protected $appends = ['rolename'];       // 表里没有的字段


     //处理订单未处理金额
    public function getRoleNameAttribute()
    {
        $role = $this->attributes['role'];  // $this->attributes表的字段属性
        $rolename = '';
        switch ($role){
            case 1:
                $rolename = '服务员';
                break;
            case 2:
                $rolename = '经理';
                break;
            case 3:
                $rolename = '前台';
                break;
            case 0:
                $rolename = '财务';
                break;
            default:
                $rolename = '服务员';
                break;
        }

        return $rolename;
    }
}